package com.liyuxiang.graph.service;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;

/**
 * AI性能监控服务
 */
@Service
public class PerformanceMonitorService {
    
    private static final Logger logger = LoggerFactory.getLogger(PerformanceMonitorService.class);
    
    @Autowired
    private StringRedisTemplate redisTemplate;
    
    // 内存中的性能计数器
    private final AtomicLong intentRecognitionCount = new AtomicLong(0);
    private final AtomicLong conversationHandlingCount = new AtomicLong(0);
    private final AtomicLong cacheHitCount = new AtomicLong(0);
    private final AtomicLong cacheMissCount = new AtomicLong(0);
    
    // 响应时间统计
    private final Map<String, Long> responseTimes = new ConcurrentHashMap<>();
    
    /**
     * 记录意图识别性能
     */
    public void recordIntentRecognition(long responseTime, boolean cacheHit) {
        intentRecognitionCount.incrementAndGet();
        if (cacheHit) {
            cacheHitCount.incrementAndGet();
        } else {
            cacheMissCount.incrementAndGet();
        }
        
        responseTimes.put("intent_" + System.currentTimeMillis(), responseTime);
        
        // 定期清理旧数据（保留最近100条）
        if (responseTimes.size() > 100) {
            responseTimes.clear();
        }
        
        // 记录到Redis
        try {
            redisTemplate.opsForValue().set("perf:intent:count", 
                String.valueOf(intentRecognitionCount.get()), Duration.ofHours(24));
            redisTemplate.opsForValue().set("perf:intent:avg_time", 
                String.valueOf(responseTime), Duration.ofHours(24));
        } catch (Exception e) {
            logger.warn("保存性能数据到Redis失败: {}", e.getMessage());
        }
    }
    
    /**
     * 记录对话处理性能
     */
    public void recordConversationHandling(long responseTime, boolean cacheHit) {
        conversationHandlingCount.incrementAndGet();
        if (cacheHit) {
            cacheHitCount.incrementAndGet();
        } else {
            cacheMissCount.incrementAndGet();
        }
        
        responseTimes.put("conv_" + System.currentTimeMillis(), responseTime);
        
        try {
            redisTemplate.opsForValue().set("perf:conversation:count", 
                String.valueOf(conversationHandlingCount.get()), Duration.ofHours(24));
            redisTemplate.opsForValue().set("perf:conversation:avg_time", 
                String.valueOf(responseTime), Duration.ofHours(24));
        } catch (Exception e) {
            logger.warn("保存性能数据到Redis失败: {}", e.getMessage());
        }
    }
    
    /**
     * 获取性能统计信息
     */
    public String getPerformanceStats() {
        double cacheHitRate = 0;
        long totalRequests = intentRecognitionCount.get() + conversationHandlingCount.get();
        if (totalRequests > 0) {
            cacheHitRate = (double) cacheHitCount.get() / totalRequests * 100;
        }
        
        double avgResponseTime = responseTimes.values().stream()
                .mapToLong(Long::longValue)
                .average()
                .orElse(0.0);
        
        return String.format(
            "性能统计 - 意图识别: %d次, 对话处理: %d次, 缓存命中率: %.2f%%, 平均响应时间: %.0fms",
            intentRecognitionCount.get(),
            conversationHandlingCount.get(),
            cacheHitRate,
            avgResponseTime
        );
    }
    
    /**
     * 定期打印性能统计（可以配合定时任务使用）
     */
    public void logPerformanceStats() {
        logger.info(getPerformanceStats());
    }
}